package com.itheima.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    @RequestMapping("login")
    public Result login(HttpSession session, HttpServletResponse response, @RequestBody Map<String, String> map){
        //1. 验证码  和redis中的验证码 进行比对
        String telephone = map.get("telephone");
        String validateCode = map.get("validateCode");
        if (StringUtils.isEmpty(validateCode)){
            return Result.fail(MessageConstant.VALIDATECODE_ERROR);
        }
        Jedis jedis = jedisPool.getResource();
        try {
            String redisCode  = jedis.get("login_" + telephone);
            if (StringUtils.isEmpty(redisCode) || !validateCode.equals(redisCode)){
                return Result.fail(MessageConstant.VALIDATECODE_ERROR);
            }
            Member member = this.memberService.findByPhone(telephone);
            if (member == null){
                //注册新用户
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                this.memberService.save(member);
            }

            //3. 保存登录信息  session 里面保存   session.setAttribute("login_user",member);
            //将用户的手机号 写入浏览器的cookie里面，下一次请求的时候，可以从cookie里面获取到用户的手机号
            //一般情况下，手机号 尽量加密，不要存储明文
            Cookie cookie = new Cookie("login_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(30*24*60*60);
            response.addCookie(cookie);
            //redis保存登录信息
            String memberJson = JSON.toJSONString(member);
            jedis.setex(telephone,60*30,memberJson);

            return Result.success(MessageConstant.LOGIN_SUCCESS,null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(MessageConstant.VALIDATECODE_ERROR);
        } finally {
            jedis.close();
        }

    }
}
